# 通过ip请求淘宝的一个接口获取到省份和运营商
# - 接口：https://ip.taobao.com/outGetIpInfo?accessKey=alibaba-inc&ip=要查询的ip地址
# - 每一行变成这种形式保存到文件
# - 格式：ip,中国,湖南,电信
import requests

# 要查询的IP地址
ip = input("请输入要查询的ip地址:")
url = f"https://ip.taobao.com/outGetIpInfo?accessKey=alibaba-inc&ip={ip}"
print(url)

try:
     # 发送HTTP请求
    response = requests.get(url)
    print(response)
    dic = response.json()
    print(dic)
# #
    # 解析获取到的省份和运营商信息
    province = dic["data"]["region"]
    isp = dic["data"]["isp"]
    country = dic['data']['country']
    print("省份:", province)
    print("运营商:", isp)
    print("国家:",country)
    # 格式化为字符串
    line = f"{ip},{country},{province},{isp}"

    # 保存到文件
    filename = "result.txt"
    with open(filename, 'a',encoding="utf-8") as file:
        file.write(line + '\n')
        print("保存成功！")
except requests.RequestException as e:
    print("请求接口失败:", e)
except Exception as e:
    print("发生错误:", e)